<?php

/**
 *@作者:MissZhang
 *@邮箱:<787727147@qq.com>
 *@创建时间:2021/9/30 上午10:59
 *@说明:订单控制器
 */
namespace app\store\controller;


use app\common\model\FosterOrder;
use app\common\util\AdminException;
use think\App;
use think\facade\View;
use think\facade\Db;

class Order extends Base
{
    //订单列表
    public function index(){
        // 搜索条件
        $where[] = ['store_id','=',$this->dianpu_id];
        $order_status= input('order_status');
        $key_type = input('key_type');
        $keyword = input('keyword');
        if ($order_status){
            $where[]=['order_status','=',$order_status];
        }
        if ($keyword){
            if ($key_type=='mobile'){
                $ids=Db::name('users')->whereLike('mobile',"%$keyword%")->column('user_id');
                $where[]=['user_id','in',$ids];
            }elseif($key_type=='realname'){
                $ids=Db::name('users')->whereLike('realname',"%$keyword%")->column('user_id');
                $where[]=['user_id','in',$ids];
            }else{
                $where[]=['order_sn','like',"%$keyword%"];
            }
        }
        $list = \app\common\model\Order::where($where)
            ->whereBetween('add_time',"$this->begin,$this->end")
            ->order('order_id desc')
            ->paginate([
            'query'=>['key_type'=>$key_type,'keyword'=>$keyword,'order_status'=>$order_status],
            'list_rows'=>$this->page_size
        ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //导出订单
    public function export_order()
    {
        //搜索条件
        $order_ids = input('order_ids');
        // 搜索条件
        $where[] = ['store_id','=',$this->dianpu_id];
        if($order_ids){
            $where[] = ['order_id','in', $order_ids];
        }else{
            $order_status= input('order_status');
            $key_type = input('key_type');
            $keyword = input('keyword');
            if ($order_status){
                $where[]=['order_status','=',$order_status];
            }
            if ($keyword){
                if ($key_type=='mobile'){
                    $ids=Db::name('users')->whereLike('mobile',"%$keyword%")->column('user_id');
                    $where[]=['user_id','in',$ids];
                }elseif($key_type=='realname'){
                    $ids=Db::name('users')->whereLike('realname',"%$keyword%")->column('user_id');
                    $where[]=['user_id','in',$ids];
                }else{
                    $where[]=['order_sn','like',"%$keyword%"];
                }
            }
        }
        $orderList = \app\common\model\Order::where($where)
            ->whereBetween('add_time',"$this->begin,$this->end")
            ->order('order_id desc')->select();
        $orders=[];
        foreach ($orderList as $val){
            $map['order_sn']=' '.$val['order_sn'];
            $map['mobile']=' '.$val['user']['mobile'];
            $map['mobile_realname']=$val['user']['realname']?:'无';
            $map['user_note']=$val['user_note'];
            $map['consignee']=$val['consignee'];
            $map['mobile1']=' '.$val['mobile'];
            $map['all_address']=$val['all_address'];
            $map['total_amount']=$val['total_amount'];
            $map['ship_price']=$val['ship_price'];
            $map['pay_name']=$val['pay_name'];
            $map['order_amount']=$val['order_amount'];
            $map['order_status_text']=$val['order_status_text'];
            $map['add_time']=$val['add_time'];
            $map['shipping_name']=$val['shipping_name'];
            $map['shipping_number']=' '.$val['shipping_number'];
            $orders[]=$map;
        }
        $xlsCell  = [
            ['mobile','会员手机'],
            ['mobile_realname','真实姓名'],
            ['order_sn','订单编号'],
            ['consignee','收货人姓名'],
            ['mobile1','收货人电话'],
            ['all_address','收货地址'],
            ['user_note','买家备注'],
            ['pay_name','支付方式'],
            ['total_amount','订单总额'],
            ['ship_price','运费'],
            ['order_amount','应付总额'],
            ['order_status_text','订单状态'],
            ['add_time','创建时间'],
            ['shipping_name','快递公司'],
            ['shipping_number','快递单号'],
        ];
        exportExcel("订单",$xlsCell,$orders);
        storeLog("导出订单");
        exit();
    }
    //订单详情
    public function order_detail(){
        $order_id=input('order_id');
        if (empty($order_id)){
            $this->error('订单不存在');
        }
        $order_model=new \app\common\model\Order();
        $info=$order_model->where(['order_id'=>$order_id,'store_id'=>$this->dianpu_id])->find();
        if (empty($info)){
            $this->error('订单不存在');
        }
        $shipping=config('app.shipping');
        View::assign('info', $info);
        View::assign('shipping', $shipping);
        return view();
    }
    public function order_upload(){
        $file = request()->file('file');
        if ($file){
            $info = \think\facade\Filesystem::putFile('ship',$file);
            $shipping=config('app.shipping');
            $arr=array_flip($shipping);
            if($info){
                $k=0;
                //获取文件后缀
                $ext=explode('.',$info);
                $filename=UPLOAD_PATH.$info;
                require_once root_path('vendor/PHPExcel').'PHPExcel.php';
                require_once root_path('vendor/PHPExcel').'/PHPExcel/IOFactory.php';
                if ($ext[1]=='xls'){
                    //use excel2007 for 2007 format
                    try {
                        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                    } catch (\PHPExcel_Reader_Exception $e) {
                        $this->error($e->getMessage());
                    }
                }else if ($ext[1]=='xlsx'){
                    //use excel2007 for 2007 format
                    try {
                        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                    } catch (\PHPExcel_Reader_Exception $e) {
                        $this->error($e->getMessage());
                    }
                }else{
                    $this->error("请选择xls或者xlsx文件");
                }
                //$filename可以是上传的文件，或者是指定的文件
                try {
                    $objPHPExcel = $objReader->load('.' . $filename);
                } catch (\PHPExcel_Reader_Exception $e) {
                    $this->error($e->getMessage());
                }
                try {
                    $sheet = $objPHPExcel->getSheet(0);
                } catch (\PHPExcel_Exception $e) {
                    $this->error($e->getMessage());
                }
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $log=true;
                for ($i=2;$i<=$highestRow;$i++){
                    $a = $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();//获取A列的值 订单编号
                    $a = trim($a, chr(0xc2) . chr(0xa0));
                    $b = $objPHPExcel->getActiveSheet()->getCell("Q".$i)->getValue();//获取B列的值 快递公司
                    $c = $objPHPExcel->getActiveSheet()->getCell("R".$i)->getValue();//获取C列的值 快递单号
                    $order_sn=trim($a);
                    $order=\app\common\model\Order::where('order_sn',$order_sn)->find();
                    if($order && $order['order_status']>0 && $b && $c){
                        $order_update['shipping_code']=$arr[$b];
                        $order_update['shipping_name']=$b;
                        $order_update['shipping_number']=$c;
                        if ($order['order_status']==1){
                            $order_update['shipping_time']=time();
                            $order_update['order_status']=2;
                        }
                        $order->save($order_update);
                        unset($order_update);
                        $k++;
                    }
                }
                if ($log){
                    @unlink('.'.$filename);//删除文件
                    $this->success('操作成功,共匹配'.$k.'条记录!');
                }else{
                    $this->error("操作失败");
                }
            }else{
                $this->error("文件上传失败");
            }
        }else{
            $this->error("请选择文件");
        }
    }
    //订单发货
    public function order_send(){
        $order_id=input('order_id');//订单id
        $shipping_code=input('shipping_code');//快递编码
        $shipping_name=input('shipping_name');//快递公司
        $shipping_number=input('shipping_number');//快递单号
        $data=input('post.');
        if (empty($order_id)){
            throw new AdminException('提交参数有误');
        }
        $order=\app\common\model\Order::where("store_id=$this->dianpu_id and order_id={$order_id}")->find();
        if (empty($order)){
            throw new AdminException('订单不存在');
        }
        if (empty($shipping_code)){
            throw new AdminException('请选择快递编码');
        }
        if (empty($shipping_name)){
            throw new AdminException('快递公司不能为空');
        }
        if (empty($shipping_number)){
            throw new AdminException('快递单号不能为空');
        }
        if ($order->order_status==1){
            $data['shipping_time']=time();
            $data['order_status']=2;
        }
        $res=$order->save($data);
        if ($res){
            storeLog("订单发货");
            throw new AdminException('操作成功',1);
        }else{
            throw new AdminException('操作失败或没有任何修改');
        }
    }
    //订单打印
    public function order_print(){
        $order_id=input('order_id');
        if (empty($order_id)){
            $this->error('提交参数有误');
        }
        $info=\app\common\model\Order::where("store_id=$this->dianpu_id and order_id={$order_id}")->find();
        if (empty($info)){
            throw new AdminException('订单不存在');
        }
        View::assign('info', $info);
        return view();
    }
    //认养订单列表
    public function foster_index(){
        // 搜索条件
        $where[] = ['store_id','=',$this->dianpu_id];
        $pay_code= input('pay_code');
        $order_status= input('order_status');
        $key_type = input('key_type');
        $keyword = input('keyword');
        if ($pay_code){
            $where[]=['pay_code','=',$pay_code];
        }
        if ($order_status){
            $where[]=['order_status','=',$order_status];
        }
        if ($keyword){
            if ($key_type=='mobile'){
                $ids=Db::name('users')->whereLike('mobile',"%$keyword%")->column('user_id');
                $where[]=['user_id','in',$ids];
            }elseif($key_type=='realname'){
                $ids=Db::name('users')->whereLike('realname',"%$keyword%")->column('user_id');
                $where[]=['user_id','in',$ids];
            }else{
                $where[]=['order_sn','like',"%$keyword%"];
            }
        }
        $list = FosterOrder::where($where)
            ->whereBetween('add_time',"$this->begin,$this->end")
            ->order('order_id desc')
            ->paginate([
                'query'=>['pay_code'=>$pay_code,'key_type'=>$key_type,'keyword'=>$keyword,'order_status'=>$order_status],
                'list_rows'=>$this->page_size
            ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }
    //导出认养订单
    public function export_foster_order(){
        //搜索条件
        $order_ids = input('order_ids');
        // 搜索条件
        $where[] = ['store_id','=',$this->dianpu_id];
        if($order_ids){
            $where[] = ['order_id','in', $order_ids];
        }else{
            $pay_code= input('pay_code');
            $order_status= input('order_status');
            $key_type = input('key_type');
            $keyword = input('keyword');
            if ($pay_code){
                $where[]=['pay_code','=',$pay_code];
            }
            if ($order_status){
                $where[]=['order_status','=',$order_status];
            }
            if ($keyword){
                if ($key_type=='mobile'){
                    $ids=Db::name('users')->whereLike('mobile',"%$keyword%")->column('user_id');
                    $where[]=['user_id','in',$ids];
                }elseif($key_type=='realname'){
                    $ids=Db::name('users')->whereLike('realname',"%$keyword%")->column('user_id');
                    $where[]=['user_id','in',$ids];
                }else{
                    $where[]=['order_sn','like',"%$keyword%"];
                }
            }
        }
        $orderList = FosterOrder::where($where)
            ->whereBetween('add_time',"$this->begin,$this->end")
            ->order('order_id desc')
            ->select();
        $orders=[];
        foreach ($orderList as $val){
            $map['mobile']=' '.$val['user']['mobile'];
            $map['mobile_realname']=$val['user']['realname']?:'无';
            $map['order_sn']=' '.$val['order_sn'];
            $map['goods_name']=$val['goods_name'];
            $map['day_sy']=' '.$val['day_sy'];
            $map['speed']=' '.$val['speed'];
            $map['sy_day']=' '.$val['sy_day'];
            $map['yield']=' '.$val['yield'];
            $map['user_note']=$val['user_note'];
            $map['pay_name']=$val['pay_name']?:'---';
            $map['order_amount']=$val['total_amount'];
            $map['order_status_text']=$val['order_status_text'];
            $map['add_time']=$val['add_time'];
            $orders[]=$map;
        }
        $xlsCell  = [
            ['mobile','会员手机'],
            ['mobile_realname','真实姓名'],
            ['order_sn','订单编号'],
            ['goods_name','商品名称'],
            ['day_sy','每日收益'],
            ['speed','加速值'],
            ['sy_day','收益周期'],
            ['yield','产量'],
            ['user_note','买家备注'],
            ['pay_name','支付方式'],
            ['order_amount','应付总额'],
            ['order_status_text','订单状态'],
            ['add_time','创建时间'],
        ];
        exportExcel("认养订单",$xlsCell,$orders);
        storeLog("导出认养订单");
        exit();
    }
    //认养订单详情
    public function foster_order_detail(){
        $order_id=input('order_id');
        if (empty($order_id)){
            $this->error('提交参数有误');
        }
        $where[] = ['store_id','=',$this->dianpu_id];
        $where[] = ['order_id','=',$order_id];
        $info=FosterOrder::where($where)->find();
        if (empty($info)){
            $this->error('订单不存在');
        }
        View::assign('info', $info);
        return view();
    }
    //认养订单打印
    public function foster_order_print(){
        $order_id=input('order_id');
        if (empty($order_id)){
            $this->error('提交参数有误');
        }
        $where[] = ['store_id','=',$this->dianpu_id];
        $where[] = ['order_id','=',$order_id];
        $info=FosterOrder::where($where)->find();
        if (empty($info)){
            $this->error('订单不存在');
        }
        View::assign('info', $info);
        return view();
    }
}
